<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽上传图片</title>
    <style>
        .drag-area {
            width: 300px;
            height: 200px;
            border: 2px dashed #ccc;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 1rem;
            background-color: #f9f9f9;
        }
        .preview-container {
            display: grid;
            gap: 1rem;
        }
        img {
            max-width: 100%;
            height: auto;
        }
    </style>
</head>
<body>

<div class="drag-area" id="uploadArea">
    <p>拖拽图片到这里上传</p>
</div>

<div class="preview-container" id="previewContainer"></div>

<div id="result"></div>

<script>
    const uploadArea = document.getElementById('uploadArea');
    const previewContainer = document.getElementById('previewContainer');
    const resultContainer = document.getElementById('result');

    // 获取CSRF Token
    function getCsrfToken() {
        return document.querySelector('[name=csrfmiddlewaretoken]').value;
    }

    // 设置拖拽区域样式
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.stopPropagation();
        uploadArea.style.borderColor = '#3498db';
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        e.stopPropagation();
        uploadArea.style.borderColor = '#ccc';

        const files = e.dataTransfer.files;

        for (const file of files) {
            if (file.type.startsWith('image/')) {
                previewImage(file);
            } else {
                alert('只能上传图片文件！');
            }
        }
    });

    function previewImage(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            const img = document.createElement('img');
            img.src = e.target.result;
            previewContainer.appendChild(img);

            // 发送Ajax请求进行文件上传
            uploadFile(file, (response) => {
                if (response.success) {
                    resultContainer.innerHTML += `<p>文件名: ${response.files[0].name}, 大小: ${response.files[0].size} B</p>`;
                    resultContainer.innerHTML += `<img src="${response.files[0].url}" alt="Preview" style="max-width: 100px;">`;
                } else {
                    alert('文件上传失败！');
                }
            });
        };
        reader.readAsDataURL(file);
    }

    // 发送Ajax请求进行文件上传
    function uploadFile(file, callback) {
        const formData = new FormData();
        formData.append('file', file);

        fetch('/upload/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCsrfToken(),
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => callback(data))
        .catch(error => console.error('Error:', error));
    }

    // 监听文件输入
    uploadArea.addEventListener('click', () => {
        const input = document.createElement('input');
        input.type = 'file';
        input.multiple = true;

        input.onchange = (e) => {
            for (const file of e.target.files) {
                if (file.type.startsWith('image/')) {
                    previewImage(file);
                } else {
                    alert('只能上传图片文件！');
                }
            }
        };

        input.click();
    });
</script>

</body>
</html>